package com.lkm.market2_0.m_imple.steelyarddata;

import com.lkm.frame.P;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.javatool.lang.ListRingBuffer;
import com.lkm.javatool.lang.RingBuffer;
import com.lkm.javatool.lang.RunnablePR;
import com.lkm.market2_0.ExpandConfig;
import com.lkm.market2_0.entity.ResponEntity;
import com.lkm.market2_0.help.UIP;
import com.lkm.market2_0.netapi.Api;
import com.lkm.market2_0.task.DefaultTaskExecutor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;



class UpOrdersTask extends TaskAdapter<Object[], Void, Boolean> {

    public static String taskID() {
        return UpOrdersTask.class.getName();
    }

    public UpOrdersTask() {
        super(new DefaultTaskExecutor(true), taskID(), ExpandConfig.instance.getTaskManager2());
    }


    
    protected String[] getAllUpDateFiles() {
        File dir = new File(ExpandConfig.instance.getOrderTempFileDir());
//                   new File( FileSystem.getRederPath(FileSystem.FileLocal.ExternalFilesDir, "orderTempFile", MyApplication.application));

        File[] updateFiles = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().startsWith("cahceOrders-update");
            }
        });
        if (updateFiles == null) {
            return new String[0];
        }
        String[] updateFilesName = new String[updateFiles.length];
        for (int i = 0; i < updateFiles.length; i++) {
            updateFilesName[i] = updateFiles[i].getAbsolutePath();
        }
        return updateFilesName;
    }



    
    
    protected String getUpDateFileJson(String disFile) {
        RingBuffer<String> jsons = null;
        BufferedReader jsonf = null;
        try {
            jsonf = new BufferedReader(new FileReader(disFile));

            
            jsons = new ListRingBuffer<String>(20000);
            String[] remveItemTemp = new String[1];
            String[] addItemTemp = new String[1];
            for (; ; ) {
                String itemjson = jsonf.readLine();
                if (itemjson == null)
                    break;



                addItemTemp[0] = itemjson;
                jsons.add(addItemTemp, 0, 1);

            }
            jsonf.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuilder jsonBuilder = new StringBuilder("");
        if (jsons != null) {
            String[] getItemTemp = new String[1];

            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                if (jsons.get(getItemTemp, 0, 1) < 1) {
                    if (jsonBuilder.length() > 0) {
                        jsonBuilder.append("]");
                    }
                    break;
                }
                if (i == 0) {
                    jsonBuilder.append("[");
                } else {
                    jsonBuilder.append(",");
                }
                jsonBuilder.append(getItemTemp[0]);
            }

        }
        return jsonBuilder.toString();
    }



    protected boolean upUpDateJson(String json) {

        boolean isSuccess = false;

        String res = Api.upOrderBat(json, null);
        if (res == null) {
            try {
                Thread.sleep(3 * 1000);
            } catch (Exception e) {
            }
        }
        ResponEntity responEntity = ResponEntity.fromJson(res, null, "");
        if (responEntity.isSuccess()) {
            isSuccess = true;

        }

        return isSuccess;
    }

    

    @Override
    public void doExecuting(Object[] param) {
        super.doExecuting(param);
        mTaskExecutor.executor(new RunnablePR<Object[], Void>() {
            @Override
            public Void run(Object[] param) {

                String[] disFiles = getAllUpDateFiles();
                if(CollectionHelp.isEmpty(disFiles)){
                    mTaskExecutor.post(new Runnable() {
                        @Override
                        public void run() {
                            LinkBus.sendBroadcast(new OnOrderUpStateEvent(0));
                        }
                    });
                    UpOrdersTask.this.complete(true);
                    return null;
                }
                mTaskExecutor.post(new Runnable() {
                    @Override
                    public void run() {
                        LinkBus.sendBroadcast(new OnOrderUpStateEvent(1));
                    }
                });

                boolean hasFial = false;
                
                for (String disFile : disFiles) {
                    if (P.isDebug()) {
                        if (UIP.isPrint()) {
                            UIP.p("UP上报台秤数据：" + disFile, "");
                        }
                    }

                    String json = getUpDateFileJson(disFile);
                    if (StringHelp.isEmpty(json)) {
                        new File(disFile).delete();
                        continue;
                    }
                    
                    boolean isSuccess = upUpDateJson(json);
                    if (isSuccess) {
                        if (ExpandConfig.instance.isLogOrderData()) {
                            boolean isCopyOk = false;

                            File disF = new File(disFile);
                            disF.renameTo(new File(ExpandConfig.instance.getOrderTempFileDir() + File.separator + "LOG_" + disF.getName()));
//                                    isCopyOk = FileHelper.copyRecursive(new File(disFile),null,UpdateDateTask.this);





                        } else {
                            new File(disFile).delete();
                        }
                    } else {
                        if (P.isDebug()) {
                            if (UIP.isPrint()) {
                                UIP.p("UP上报台秤数据：上传失败，" + disFile, "");
                            }
                        }
                        hasFial = true;
                        continue;
                    }
                }

                if (hasFial) {
                    
                    UpOrdersTask.this.complete(false);
                } else {
                    
                    UpOrdersTask.this.complete(true);
                }


                if (hasFial) {
                    mTaskExecutor.post(new Runnable() {
                        @Override
                        public void run() {
                            LinkBus.sendBroadcast(new OnOrderUpStateEvent(3));
                        }
                    });
                }else {
                    mTaskExecutor.post(new Runnable() {
                        @Override
                        public void run() {
                            LinkBus.sendBroadcast(new OnOrderUpStateEvent(2));
                        }
                    });
                }
                if(CollectionHelp.isEmpty( getAllUpDateFiles())){
                    mTaskExecutor.post(new Runnable() {
                        @Override
                        public void run() {
                            LinkBus.sendBroadcast(new OnOrderUpStateEvent(0));
                        }
                    });
                    return null;
                }

                return null;
            }
        }, param);


    }

}


